package com.shipwe.loans.ui.fragment

import android.view.LayoutInflater
import android.view.View
import com.shipwe.loans.R
import com.shipwe.loans.databinding.FragmentLuckyDrawBinding
import com.shipwe.loans.http.IHttpCallback
import com.shipwe.loans.pro.ShipweFragment
import com.shipwe.loans.ui.activity.ActivityMain
import com.shipwe.loans.ui.activity.ActivityUserPoints
import com.shipwe.loans.utils.dialog.LuckyDrawGiftDialog
import com.shipwe.loans.utils.event.AppEventData
import com.shipwe.loans.utils.event.AppEventPointType
import com.shipwe.loans.utils.helper.CustomConfigsHelper
import com.shipwe.loans.utils.helper.CustomDataHelper
import com.shipwe.loans.utils.helper.UserPointsHelper
import org.json.JSONObject

/**
 * Shipwe
 * @Author wwdeng
 * @CreateTime: 2024/11/14 10:32
 * @Annotation：抽奖
 */
class FragmentLuckyDraw: ShipweFragment() {
    lateinit var binding: FragmentLuckyDrawBinding
    override fun getShipweRootView(inflater: LayoutInflater): View {
        binding = FragmentLuckyDrawBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initShipweView() {
        rootViewBinding.rootLayout.setBackgroundResource(R.drawable.page_login_bg)
        setShipweTitleBarVisibility(View.VISIBLE)
        setShipweBackBtnRes(R.drawable.menu_black)
        setShipweRightBtnRes(R.drawable.customer_black)
        setShipweTextTitle(getString(R.string.lucky_draw_title))
    }

    override fun initShipweListener() {
        //菜单
        rootViewBinding.rootBack.setOnClickListener {
            (getAct() as ActivityMain).showMainMenuFragment("Lucky Draw Page")
        }
        //客服
        rootViewBinding.rootCustomer.setOnClickListener {
            showCustomerDialog("Lucky Draw Page")
            appEventPointRequestAction(AppEventPointType.CLICK.SHIPWE_CLICK_CUSTOMER,"Lucky Draw Page")
        }
        //积分明细
        binding.luckyDrawPointsDetails.setOnClickListener{
            onIntent(ActivityUserPoints::class.java)
        }
        //抽奖
        binding.luckyDrawOpen.setOnClickListener {
            onLuckyDrawSaveUserPointsAction("luckyDrawUse","-${CustomConfigsHelper.getShipweLuckyDrawPointsUse()}",true)
        }
    }

    override fun initShipweData() {
        //今日剩余抽奖次数
        val luckyDrawCount = CustomDataHelper.getShipweCustomLuckyDrawCount()
        binding.luckyDrawChances.text = String.format(getString(R.string.lucky_draw_chances_left),"$luckyDrawCount")

        //抽奖需要消耗的积分
        val needUsePoints = CustomConfigsHelper.getShipweLuckyDrawPointsUse().toInt()
        //当前剩余积分
        val userPoints = UserPointsHelper.getShipweUserPoints()
        //积分不足
        if (userPoints < needUsePoints){
            binding.luckyDrawOpen.setBackgroundResource(R.drawable.page_lucky_draw_open_normal)
            binding.luckyDrawText.text = getString(R.string.lucky_draw_not_enough)
            binding.luckyDrawPointsTime.visibility = View.GONE
            binding.luckyDrawOpen.isEnabled = false
        } else {
            //今日剩余抽奖次数 <= 0
            if (luckyDrawCount <= 0){
                binding.luckyDrawOpen.setBackgroundResource(R.drawable.page_lucky_draw_open_normal)
                binding.luckyDrawText.text = getString(R.string.lucky_draw_try_again_tomorrow)
                binding.luckyDrawPointsTime.visibility = View.GONE
                binding.luckyDrawOpen.isEnabled = false
            } else {
                binding.luckyDrawOpen.setBackgroundResource(R.drawable.page_lucky_draw_open_select)
                binding.luckyDrawText.text = getString(R.string.lucky_draw_open)
                binding.luckyDrawPointsTime.visibility = View.VISIBLE
                binding.luckyDrawPointsTime.text = String.format(getString(R.string.lucky_draw_use_points),"$needUsePoints")
                binding.luckyDrawOpen.isEnabled = true
            }
        }
    }

    /**
     * 消耗、获取积分
     */
    private fun onLuckyDrawSaveUserPointsAction(useType: String, points: String, isUse: Boolean){
        UserPointsHelper.onSaveUserPointsAction(useType, getString(R.string.points_use_info_lucky_draw),points,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                when(data.optInt("code")) {
                    0 -> {//成功
                        if (isUse){//抽奖消耗
                            showLuckyDrawAnimDialog()
                        } else {//抽奖得到
                            //今日剩余抽奖次数
                            val luckyDrawCount = CustomDataHelper.getShipweCustomLuckyDrawCount()
                            //保存剩余次数和记录上次抽奖时间
                            CustomDataHelper.saveShipweCustomLuckyDrawCount("${luckyDrawCount - 1}")
                        }
                    }
                    else -> {
                        showShipweToast(data.optString("msg"))
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
                showShipweToast(error.optString("errorMsg"))
            }

            override fun onRequestFinish() {
            }
        })
    }

    /**
     * 获得积分dialog
     */
    private fun showLuckyDrawAnimDialog(){
        val points = CustomConfigsHelper.getShipweLuckyDrawPoints()
        onLuckyDrawSaveUserPointsAction("luckyDrawReceived",points,false)
        val giftDialog = LuckyDrawGiftDialog(requireContext(),"Lucky Draw Received",object : LuckyDrawGiftDialog.IDialogCallback{
            override fun onClick(view: View?) {

            }
        })
        giftDialog.setCancelable(true)
        giftDialog.setCanceledOnTouchOutside(false)
        giftDialog.show()
        giftDialog.setGiftTitleText(getString(R.string.lucky_draw_congratulations))
        giftDialog.setGiftPointText(String.format(getString(R.string.points_count), points))
        giftDialog.setGiftPointTips(getString(R.string.lucky_draw_success_tips))
        giftDialog.setGiftButtonText(getString(R.string.click_get))
    }

    override fun onShipwePublishEvent(event: AppEventData) {
        super.onShipwePublishEvent(event)
        if (event.eventType == AppEventData.TYPE.SHIPWE_CUSTOM_DATA_REFRESHED){
            initShipweData()
        }
    }
    override fun onStart() {
        super.onStart()
        appEventPointRequestAction(AppEventPointType.PAGE.SHIPWE_PAGE_LUCKY_DRAW_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        appEventPointRequestAction(AppEventPointType.PAGE.SHIPWE_PAGE_LUCKY_DRAW_END)
    }

}